package ypmits.components.listbox {
	import ypmits.components.Component;
	import ypmits.components.IComponent;
	import ypmits.components.listbox.input.ListBoxInput;
	import ypmits.components.listbox.view.ListBoxView;
	import ypmits.components.listbox.view.item.ListBoxItemData;

	import flash.display.Sprite;
	import flash.events.Event;

	/**
	 * @author Dave Lenz
	 */
	public class ListBox extends Component implements IComponent, IListBox {

		public var view : ListBoxView;
		private var input : ListBoxInput;

		
		
		/**
		 * @example var listbox : ListBox = new ListBox( new ListBoxInput() );
		 */
		public function ListBox( input : ListBoxInput = null ) 
		{
			super( );
			
			if( input && input is ListBoxInput ) {
				this.input = input;
				
				setView();
				
			} else {
				throw new Error( "ERROR! The ListBox-constructor expects data of type 'ListBoxInput'" );
			}
		}

		
		
		public function setData( data : ListBoxInput ) : void 
		{
			input = data;
			
			setView();
		}

		
		
		private function setView( ) : void 
		{
			view ? view.dispose() : null;

			input.filterchooser = this;

			view = new ListBoxView( input );
			view.addEventListener( Event.RESIZE, resize );
			view.addEventListener( Event.ADDED_TO_STAGE, init );
			view.addEventListener( Event.CLOSE, closeHandler );
			addChild( view );
		}

		
		
		private function closeHandler( e : Event ) : void 
		{
			hide( );
		}

		
		
		private function resize( e : Event ) : void 
		{
			dispatchEvent( e.clone( ) );
		}

		
		
		private function init( e : Event ) : void 
		{
			dispatchEvent( new Event( Event.INIT ) );
		}

		
		
		override public function get height() : Number 
		{
			if( view && view.grabber ) return Number( view.grabber.y + ListBoxView.GRABBERHEIGHT );
			return view.height;
		}

		
		
		override public function set height(value : Number) : void {
			input.height = value;
			redraw();
		}

		
		
		override public function show() : void 
		{
			alpha = 1;
			visible = true;
		}

		
		
		override public function hide() : void 
		{
			alpha = 0;
			visible = false;
			
			dispatchEvent( new Event( Event.CLOSE, true ) );
		}

		
		
		public function addItem( item : ListBoxItemData ) : void 
		{
			view.addItem( item );
		}
		
		
		public function addItems(items : Array) : void {
			view.addItems( items );
		}

		
		
		public function get content() : Sprite 
		{
			return view.content;
		}

		
		
		public function set content( content : Sprite ) : void {
			view.content = content;
		}

		
		
		public function redraw( complete : Boolean = false ) : void 
		{
			view.redraw( complete );
		}

		
		
		public function setTitle( string : String ) : void 
		{
		}

		
		
		override public function get numChildren() : int 
		{
			return view.numChildren;
		}

		
		
		public function showWarning( text : String ) : void
		{
			view.showListBoxWarning( text );
		}

		
		
		public function hideWarning( ) : void
		{
			view.hideListBoxWarning( );
		}
	}
}
